package com.atguigu.process.service.impl;

import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.process.ProcessType;
import com.atguigu.process.mapper.ProcessTypeMapper;
import com.atguigu.process.service.ProcessTemplateService;
import com.atguigu.process.service.ProcessTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProcessTypeServiceImpl extends ServiceImpl<ProcessTypeMapper, ProcessType>
        implements ProcessTypeService {
    @Autowired
    private ProcessTemplateService processTemplateService;

    @Override
    public List<ProcessType> findProcessTypeAndTemplate() {
        List<ProcessType> processTypes = list();
        Map<Long, ProcessType> typeMap = processTypes.stream().collect(Collectors.toMap(
                ProcessType::getId, p -> p, (oldKey, newKey) -> newKey));
        List<ProcessTemplate> templates = processTemplateService.list();
        for(ProcessTemplate template : templates){
            Long processTypeId = template.getProcessTypeId();
            if(processTypeId != null){
                ProcessType processType = typeMap.get(processTypeId);
                if(processType != null){
                    if(processType.getProcessTemplateList() == null){
                        processType.setProcessTemplateList(new ArrayList<>());
                    }
                    processType.getProcessTemplateList().add(template);
                }
            }
        }
        return processTypes;
    }
}
